package me.evis.gae.ping4web.services.net.impl;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import me.evis.gae.ping4web.services.net.PingStatistics;
import me.evis.gae.ping4web.services.net.URLPinger;

public class URLPingerImpl implements URLPinger {

    @Override
    public PingStatistics ping(String urlString) {
        PingStatistics pingStatistics = new PingStatistics();
        pingStatistics.setUrl(urlString);
        try {
            URL url = new URL(urlString);
            //HttpURLConnection.setFollowRedirects(false);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDefaultUseCaches(false);
            connection.setUseCaches(false);
            connection.setRequestProperty("X-Ping4Web-Version", "1.0.0");
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(30000);
            
            long sendingTimeMillis = System.currentTimeMillis();
            connection.connect();
            long receivingTimeMillis = System.currentTimeMillis();
            copyResponseData(connection, pingStatistics);
            connection.disconnect();
            
            pingStatistics.setSendingDate(new Date(sendingTimeMillis));
            pingStatistics.setReceivingDate(new Date(receivingTimeMillis));
            pingStatistics.setDuration((int)(receivingTimeMillis - sendingTimeMillis));
            
        } catch (MalformedURLException e) {      
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    
        return pingStatistics;
    }

    private void copyResponseData(HttpURLConnection connection, 
                                  PingStatistics pingStatistics) 
            throws IOException {
        pingStatistics.setContentType(connection.getContentType());
        pingStatistics.setContentLength(connection.getContentLength());
        pingStatistics.setResponseDate(new Date(connection.getDate()));
        pingStatistics.setResponseCode(connection.getResponseCode());
        pingStatistics.setResponseMessage(connection.getResponseMessage());
        pingStatistics.setHeaderFields(connection.getHeaderFields());
    }
}
